# -*- coding: utf-8 -*-

from django.core.handlers.wsgi import WSGIRequest

from firstDjango.decorators import post, get
from firstDjango.exceptions import FormException
from index.common.paging import page2offset
from index.models import CommentLike, BookComment
from index.protocol.comment_protocol import CommentLikeRequest, MyLikesRequest
from index.dao.comment_dao import fetch_comments, fetch_comments_by_ids
from index.service.comment_service import comment_model2dict


@post(request_data_class=CommentLikeRequest)
def like(req: WSGIRequest, data: CommentLikeRequest):
    try:
        comment = BookComment.objects.get(id=data.comment_id)
    except BookComment.DoesNotExist:
        raise FormException("评论不存在")

    user_id = req.session.get('user').id
    if data.is_like:
        opt = CommentLike(user_id=user_id, comment=comment, book_id=comment.book_id).save
    else:
        opt = CommentLike.objects.filter(user_id=user_id, comment=comment).delete

    try:
        opt()
    except Exception as e:
        raise FormException("操作失败，请稍后再试", raw_exception=e)
    return "ok"


@get(request_data_class=MyLikesRequest)
def my_likes(req: WSGIRequest, data: MyLikesRequest):
    user_id = req.session.get('user').id
    offset, limit = page2offset(data.page, data.page_size)

    comment_ids = CommentLike.objects.filter(user_id=user_id).values_list("comment_id", flat=True)\
                      .order_by("-create_time")
    total_count = comment_ids.count()
    comment_ids = comment_ids[offset: offset + limit]
    comment_id_map = fetch_comments_by_ids(ids=list(comment_ids))
    comments = [comment_id_map.get(i) for i in comment_ids if comment_id_map.get(i)]
    comment_dicts = comment_model2dict(req, comments, lambda _: True)
    return {
        "comments": comment_dicts,
        "page": data.page,
        "page_size": data.page_size,
        "total_count": total_count
    }


